package com.fzz.netty.study.test;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.log4j.Logger;

import java.time.LocalDateTime;

/**
 * 处理文本协议数据，处理TextWebSocketFrame类型的数据，
 * websocket专门处理文本的frame就是TextWebSocketFrame
 *
 * @author fankai
 * @version 1.0
 * @date 2021/11/02 14:49
 **/

public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<Object> {
    Logger log = Logger.getLogger(TextWebSocketFrameHandler.class);


    /**
     * 接收到消息
     *
     * @param ctx
     * @param msg
     * @author fankai
     * @date 2021/11/2 14:56
     **/
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("======>>>>收到消息：" + msg);

        /**
         * writeAndFlush 接收的参数类型是Object类型，但是一般我们都是要传入管道中传数据类型，
         * 比如我们当前demo传输的就是TextWebSocketFrame类型的数据
         */
        ctx.channel().writeAndFlush(new TextWebSocketFrame("======>>>>服务时间：" + LocalDateTime.now()));
    }


    /**
     * 设备连接
     *
     * @param ctx
     * @author fankai
     * @date 2021/11/2 14:57
     **/
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("======>>>>handlerAdded：" + ctx.channel().id().asLongText());
    }


    /**
     * 断开连接
     *
     * @param ctx
     * @author fankai
     * @date 2021/11/2 14:57
     **/
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("======>>>>handlerRemoved：" + ctx.channel().id().asLongText());
    }

    /**
     * 发生异常
     *
     * @param ctx
     * @param cause
     * @author fankai
     * @date 2021/11/2 14:58
     **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("======>>>>异常发生");
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("======>>>>channelActive：" + ctx.channel().id().asLongText());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("======>>>>channelInactive：" + ctx.channel().id().asLongText());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
